# 加载数据集
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC  
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd

data=load_breast_cancer()
x,y = dataset.data,dataset.target
print(x,shape)
print(x)

# 数据标准化处理
from sklearn.preprocessing import StandardScaler
x=StandardScaler().fit_transfrom(x)
print(x)

# 使用四种核函数分别训练模型,并计算准确率
from sklearn.metrics import accuracy_score
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=420)
kernels=['linear','poly','rbf','sigmoid']
for kernel in kernels:
    model=SVC(kernel=kernel,gamma="auto",degree=1)
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    print(f'选择{kernel}核函数时，预测准确率为：{ac}')

# 多项式核函数的参数调节
from sklearn.model_selection  import StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
gamma_range=np.logspace(-10,1,20)
coef0_range=np.linspace(0,5,10)
param_grid=dict(gamma=gamma_range,coef0=coef0_range)
cv=StratifiedShufflesSplit(n_splits=5,test_size=0.3,random_state=420)
grid=GridSearchcv(SVC(kernel='poly',degree=1),param_grid=param_grid,cv=cv)
grid.fit(x,y)
print(f'最优参数值为：{grid.best_params_}')
print(f'选取该参数值时,模型的预测准确率为:{grid.best_score_}')

# 高斯基核函数的参数调节
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt

score=[]
gamma_range=np.logspace(-10,1,50)
for i in gamma_range:
    model=SVC(kernel='rbf',gamma=i)
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    score.append(ac)
plt.plot(gamma_range,score)
plt.show()
print(f'参数gamma的最优值为；{gamma_range[score.index(max(score))]}')
print(f'选取该参数值时，预测准确率为：{max(score)}')